<!--
 * @description: 编辑打卡规则
 * @Author: Coder
 * @Date: 2021-07-22 10:42:00
 * @LastEditors: Please set LastEditors
 -->
<template>
  <div class="page-miH page-bgBack">
    <!-- 子路由header -->
    <header class="l_title">
      <span style="cursor: pointer; font-size: 16px" @click="$router.go(-1)">
        <a-icon type="left" style="margin: 30px 10px 0 20px" />返回
      </span>
      <div class="flex space_center">{{ this.$route.params.id === "0" ? "新增打卡规则" : "编辑打卡规则" }}</div>
    </header>
    <!-- 内容 -->
    <a-layout-content v-if="!addFreeCard" class="editor_content">
      <div class="content">
        <a-form :form="form" class="lab_l">
          <a-form-item label="规则名称" :label-col="{ span: 3 }" :wrapper-col="{ span: 16 }" class="requireLeft">
            <a-input
              v-decorator="[
                'planName',
                {
                  rules: [{ required: true, message: '必填' }],
                  initialValue: postRules.planName
                }
              ]"
              style="width: 225px"
              placeholder="请输入打卡规则名称"
            />
          </a-form-item>
          <a-form-item label="规则类型" :label-col="{ span: 3 }" :wrapper-col="{ span: 16 }" :required="true" class="requireLeft">
            <a-radio-group v-model="postRules.planType">
              <a-row>
                <a-radio class="w110" :value="1">固定时间上下班 </a-radio>
                <span class="sub_tit" style="padding-left: 10px"> 所有人按照相同时间打卡</span>
              </a-row>
              <!-- <a-row>
                <a-radio class="w110" :value="2">按班次上下班</a-radio>
                <span class="sub_tit">不同人员按照各自排班打卡</span>
              </a-row>
              <a-row>
                <a-radio class="w110" :value="3">自由上下班</a-radio>
                <span
                  class="sub_tit"
                >所有人无时间限制,随时打卡,只统计旷工</span>
              </a-row> -->
            </a-radio-group>
          </a-form-item>
        </a-form>
      </div>
      <div class="content">
        <a-form class="lab_l">
          <!-- 打卡人员 -->
          <a-form-item label="打卡人员" :label-col="{ span: 3 }" :wrapper-col="{ span: 16 }" :required="true" class="requireLeft">
            <a-row type="flex" align="middle">
              <a-col>
                <a-button type="link" class="tc-theme pdl" @click="addUsers"> <a-icon type="plus-square" />添加 </a-button>
              </a-col>

              <a-col v-for="(item, index) in postRules.staffList" :key="item.empInfoId">
                <a-tag color="green">
                  &nbsp;&nbsp;{{ item.empInfoName }}
                  <a-icon type="close" @click="deleteUser(index, postRules.staffList)" />
                </a-tag>
              </a-col>
            </a-row>
          </a-form-item>
        </a-form>
      </div>
      <div class="content">
        <a-form class="lab_l">
          <a-form-item label="打卡地点" :label-col="{ span: 3 }" :wrapper-col="{ span: 16 }" :required="true" class="requireLeft">
            <!-- <span class="sub_tit">位置和WiFi满足任意一项即可打卡 </span> -->
          </a-form-item>
          <a-form-item label="位置" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
            <a-button type="link" class="tc-theme" @click="addCardPosition"> <a-icon type="plus-square" />添加</a-button>
            <span class="sub_tit">可添加多个打卡地点,并设置打卡范围 </span>
            <a-row v-for="(item, i) in postRules.locationList" :key="i" style="width: 100%" class="tab_item" type="flex" align="middle">
              <a-col class="mg_l20">{{ item.positionName + `    ` + item.distance + "米" }}</a-col>
              <a-col class="mg_l_o">
                <span class="tc-theme cursor" @click="deletePos(i)"> 删除 </span>
              </a-col>
            </a-row>
          </a-form-item>
          <!-- WiFi -->
          <!-- <a-form-item label="WiFi" :label-col="{ span: 3 }" :wrapper-col="{ span: 16 }">
            <a-button type="link" class="tc-theme" @click="addWIFI"> <a-icon type="plus-square" />添加</a-button>
            <span class="sub_tit">可添加多个WiFi,连接指定的WiFi即可打卡 </span>

            <template v-if="postRules.wifiList.length">
              <a-row v-for="(item, i) in postRules.wifiList" :key="i" class="tab_item" type="flex" align="middle">
                <a-col :span="10" class="pl20">{{ item.name }}</a-col>
                <a-col :span="12">{{ item.macAddr }}</a-col>
                <a-col :span="2">
                  <span class="tc-theme cursor" @click="deleteWifi(i)">
                    删除
                  </span>
                </a-col>
              </a-row>
            </template>
          </a-form-item> -->
          <!-- 打卡时间 -->
          <a-form-item label="打卡时间" :label-col="{ span: 3 }" :wrapper-col="{ span: 16 }" :required="true" class="requireLeft">
            <!-- 固定时间 -->
            <template v-if="postRules.planType === 1">
              <a-button v-if="!postRules.punchTimeList.length" type="link" class="tc-theme pdl" @click="addCardTime">
                <a-icon type="plus-square" />添加
              </a-button>
              <!-- <a-row v-if="postRules.punchTimeList.length" type="flex" align="middle" class="tab_title" style="border-top: 0">
                <a-col class="pl20" />
                <a-col />
                <a-col :span="4" class="cursor" />
              </a-row> -->
              <a-row
                v-for="(item, i) in postRules.punchTimeList"
                :key="i"
                class="tab_item"
                style="border: 0"
                type="flex"
                justify="space-between"
                align="middle"
              >
                <a-col class="pl20">
                  <a-tag v-for="(w, p) in item.workWeekList" :key="p" color="#6A66F6">{{ w }}</a-tag>
                </a-col>
                <a-col>
                  <a-row v-for="(t, j) in item.periodList" :key="j"> 上班 {{ t.startPeriod }} - 下班 {{ t.endPeriod }} </a-row>
                </a-col>
                <a-col class="fr">
                  <span class="tc-theme cursor" @click="editorPunchTime(item, i)"> 编辑 </span>
                  <a-divider type="vertical" />
                  <span class="tc-theme cursor" @click="deleteCardTime(i)"> 删除 </span>
                </a-col>
              </a-row>
            </template>
            <!--自由上下班  -->
            <template v-if="postRules.planType === 2">
              <a-button type="link" class="tc-theme" @click="addFreeTime"> <a-icon type="plus-square" />编辑排班</a-button>
            </template>
            <!-- 自由上下班 -->
            <template v-if="postRules.planType === 3">
              <a-checkbox-group v-model="workWeekList" @change="punchTime">
                <a-row type="flex" align="middle">
                  <a-col><a-checkbox value="星期一">星期一</a-checkbox></a-col>
                  <a-col><a-checkbox value="星期二">星期二</a-checkbox></a-col>
                  <a-col><a-checkbox value="星期三">星期三</a-checkbox></a-col>
                  <a-col><a-checkbox value="星期四">星期四</a-checkbox></a-col>
                  <a-col><a-checkbox value="星期五">星期五</a-checkbox></a-col>
                  <a-col><a-checkbox value="星期六">星期六</a-checkbox></a-col>
                  <a-col><a-checkbox value="星期日">星期日</a-checkbox></a-col>
                </a-row>
              </a-checkbox-group>
            </template>
          </a-form-item>
          <!-- 特殊日期 -->
          <a-form-item label="特殊日期" :label-col="{ span: 3 }" :wrapper-col="{ span: 16 }">
            <a-button type="link" class="tc-theme" @click="addCardDate"> <a-icon type="plus-square" />添加</a-button>
            <span class="sub_tit">必须打卡的日期 </span>
            <a-row class="tab_title" style="border-top: 0" />
            <a-row
              v-for="(item, i) in postRules.needPunchDateList"
              :key="i"
              class="tab_item"
              style="width: 100%"
              type="flex"
              align="middle"
            >
              <a-col class="pl20 mg_r20">{{ item.daily }}</a-col>
              <a-col>
                <a-row v-for="(d, j) in item.periodList" :key="j"> 上班 {{ d.startPeriod }} --下班 {{ d.endPeriod }} </a-row>
                {{ item.reason }}
              </a-col>
              <a-col class="mg_l_o">
                <span class="tc-theme cursor" @click="editorCardDate(item, i)"> 编辑 </span>
                <a-divider type="vertical" />
                <span class="tc-theme cursor" @click="deleteSpTime(i)"> 删除 </span>
              </a-col>
            </a-row>
            <a-button type="link" class="tc-theme" @click="addNoUseClock"> <a-icon type="plus-square" />添加</a-button>
            <span class="sub_tit">不用打卡的日期 </span>
            <a-row
              v-for="(item, i) in postRules.noNeedPunchDateList"
              :key="i + 99999999"
              class="tab_item"
              style="width: 100%"
              type="flex"
              align="middle"
            >
              <a-col class="pl20 mg_r20">{{ item.daily }}</a-col>
              <a-col>{{ item.reason }}</a-col>
              <a-col class="mg_l_o">
                <span class="tc-theme cursor" @click="editorNoUseCard(item, i)"> 编辑 </span>
                <a-divider type="vertical" />
                <span class="tc-theme cursor" @click="deleteNoUseClock(i)"> 删除 </span>
              </a-col>
            </a-row>
          </a-form-item>
          <!-- 加班规则 -->

          <!-- 节假日 -->
          <a-form-item label="排休设置" :label-col="{ span: 3 }" :wrapper-col="{ span: 16 }">
            <a-checkbox v-model="postRules.isSynchLegalHoliday"> 同步中国大陆法定节假日 </a-checkbox>
            <span class="sub_tit">自动排休 </span>
            <a style="font-size: 14px; margin: 0 16px" :disabled="!postRules.isSynchLegalHoliday" @click="visible = true">查看排休日历</a>
          </a-form-item>
        </a-form>
      </div>
      <div class="content">
        <!-- 手机提醒 -->
        <a-form class="lab_l">
          <a-form-item label="手机提醒" :label-col="{ span: 3 }" :wrapper-col="{ span: 16 }">
            <span class="mg_r10">上班前</span>
            <a-input-number style="width: 120px" v-model="postRules.remindBefore" :min="0" :formatter="value => `${value}分钟`" />
            <!-- <a-select v-model="postRules.remindBefore" style="width: 120px">
              <a-select-option :value="0">准点</a-select-option>
              <a-select-option :value="5">前5分钟</a-select-option>
              <a-select-option :value="10">前10分钟</a-select-option>
              <a-select-option :value="15">前15分钟</a-select-option>
              <a-select-option :value="20">前20分钟</a-select-option>
            </a-select> -->
            - <span class="mg_r10">下班后</span>
            <a-input-number style="width: 120px" v-model="postRules.remindAfter" :min="0" :formatter="value => `${value}分钟`" />
            <a-checkbox v-model="postRules.isRemind" style="margin-left: 12px"> 是否提醒 </a-checkbox>
            <!-- <a-select v-model="postRules.remindAfter" style="width: 120px">
              <a-select-option :value="0">准点</a-select-option>
              <a-select-option :value="10">后10分钟</a-select-option>
              <a-select-option :value="20">后20分钟</a-select-option>
              <a-select-option :value="30">后30分钟</a-select-option>
              <a-select-option :value="60">后60分钟</a-select-option>
            </a-select> -->
          </a-form-item>
          <!-- 拍照打卡 -->
          <!-- <a-form-item
            label="拍照打卡"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-checkbox
              v-model="postRules.isTakePhoto"
            >员工打卡时必须拍照</a-checkbox>
          </a-form-item> -->

          <!-- 备注图片 -->
          <!-- <a-form-item
            label="备注图片"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 16 }"
          >
            <a-checkbox
              v-model="postRules.holidays"
            >备注不允许上传本地图片,只能拍照</a-checkbox>
          </a-form-item> -->
          <!-- 范围打卡 -->
          <a-form-item label="范围打卡" :label-col="{ span: 3 }" :wrapper-col="{ span: 16 }">
            <a-radio-group v-model="postRules.punchRange">
              <a-radio :value="1"> 允许范围外打卡,记录为地点异常 </a-radio>
              <a-radio :value="3">不允许范围外打卡</a-radio>
              <!-- <a-row>

              </a-row>

              <a-row style="padding-top: 20px">

              </a-row> -->
            </a-radio-group>
          </a-form-item>
          <!-- 补办申请 -->
        </a-form>
      </div>
      <a-form class="lab_l">
        <a-form-item label="规则生效时间" :label-col="{ span: 3 }" :wrapper-col="{ span: 16 }">
          <a-radio-group v-model="postRules.takeEffect">
            <a-radio :value="2">立即生效</a-radio>
            <a-radio :value="1">明日生效</a-radio>
            <!-- <a-row>

            </a-row>
            <a-row style="padding-top: 20px">

            </a-row> -->
          </a-radio-group>
        </a-form-item>
      </a-form>
      <a-row class="editorRules_btn">
        <a-button type="primary" @click="saveNeedData">保存</a-button>
      </a-row>
    </a-layout-content>
    <a-layout-content v-if="addFreeCard">
      <check-free-time :free-card="freeCard" />
    </a-layout-content>
    <add-wifi :wifi-options="wifiOptions" @editorWifi="editorWifi($event)" />
    <no-use-clock
      :show.sync="showNoUseClock"
      :no-need-punch-date="noNeedPunchDate"
      :edit-no-use-index="editNoUseIndex"
      @handleNoNeedList="handleNoNeedList"
      @handleNoUseShow="handleNoUseShow"
    />
    <card-position :card-position-options="cardPositionOptions" @cardPos="cardPos($event)" />
    <do-work-rules :do-work-rules-options="doWorkRulesOptions" @addWorkRules="addWorkRules($event)" />
    <card-time
      v-if="timeList.periodList"
      :show-card-time="showCardTime"
      :time-list="timeList"
      :edit-index="editIndex"
      @handleTimeList="handleTimeList"
      @handleTimeShow="handleTimeShow"
    />
    <card-date
      :show.sync="showCardDate"
      :need-punch-date="needPunchDate"
      :edit-date-index="editDateIndex"
      @handleNeedList="handleNeedList"
      @handleDateShow="handleDateShow"
    />
    <!-- <users
      :show.sync="showUsers"
      :user-options="userOptions"
      @staffList="staffListCustom($event)"
    />
    <white-list
      :show.sync="showWhiteList"
      :white-options.sync="whiteOptions"
      @whiteEditors="whiteEditors($event)"
    />
    <report-user
      :show.sync="showReportList"
      :report-user-options="reportUserOptions"
      @editorReportUser="editorReportUser($event)"
    /> -->
    <employee-select :show.sync="isChooseStaff" :default-selected-keys="defaultSelectedKeys" @change="onEmployeeSelectChange" />
    <employee-select :show.sync="isChooseStaff2" :default-selected-keys="defaultSelectedKeys2" @change="onEmployeeSelectChange2" />
    <cardCalendar :visible.sync="visible" />
  </div>
</template>

<script>
import { Check, EditorRules, Common } from "@/api/check";
import EmployeeSelect from "@/components/EmployeeSelect2/employeeSelect4";
import reportUser from "./component/report-user";
import cardDate from "./component/card-date";
import cardTime from "./component/card-time";
import cardCalendar from "./component/card-calendar";
import noUseClock from "./component/nouse-clock";
import doWorkRules from "./component/do-work-rules";
import cardPosition from "./component/card-position";
import addWifi from "./component/add_wifi";
import checkFreeTime from "./component/check-free-time";
import { mapState } from "vuex";
import moment from "moment";
const initTimeList = {
  periodList: [
    {
      startPeriod: "09:00",
      endPeriod: "18:00",
      type: true,
      sort: 0,
      hasRestPeriod: false
    }
  ],
  restPeriod: {
    startPeriod: "12:00",
    endPeriod: "13:00",
    type: false,
    sort: 0
  },
  afterWorkNeedPunch: true,
  earliestPunchTime: "15",
  earlyMinute: 1,
  isAllowLateLate: false,
  isAllowedLateEarly: false,
  lateMinute: 1,
  latestPunchTime: "60",
  offWorkLateMinute: 1,
  onWorkLateMinute: 1,
  workWeekList: ["星期一", "星期二", "星期三", "星期四", "星期五"],
  latestOnPunchTime: "15",
  earliestOffPunchTime: "60"
};
const initNeed = {
  daily: moment().format("YYYY-MM-DD"),
  reason: "",
  periodList: [
    {
      startPeriod: "09:00",
      endPeriod: "18:00",
      type: true,
      sort: 0,
      hasRestPeriod: false
    }
  ],
  restPeriod: {
    startPeriod: "12:00",
    endPeriod: "13:00",
    type: false,
    sort: 0
  }
};
const initNoNeed = {
  daily: moment().format("YYYY-MM-DD"),
  reason: ""
};
const dateJson = {
  星期一: {
    k: 1,
    v: "星期一"
  },
  星期二: {
    k: 2,
    v: "星期二"
  },
  星期三: {
    k: 3,
    v: "星期三"
  },
  星期四: {
    k: 4,
    v: "星期四"
  },
  星期五: {
    k: 5,
    v: "星期五"
  },
  星期六: {
    k: 6,
    v: "星期六"
  },
  星期日: {
    k: 7,
    v: "星期日"
  }
};
export default {
  components: {
    addWifi,
    noUseClock,
    cardPosition,
    doWorkRules,
    cardTime,
    cardDate,
    checkFreeTime,
    EmployeeSelect,
    cardCalendar
  },

  data() {
    return {
      detail: {
        companyId: "",
        deptList: [],
        id: "",
        isMakeUp: false, // 是否补卡1是0否
        isOnlyPhoto: false,
        isRemind: false,
        isSynchLegalHoliday: false,
        isTakePhoto: false,
        locationList: [], // 打卡位置
        maxMakeUpCounts: 6,
        needPunchDateList: [], // 特殊日期必须打卡
        noNeedPunchDateList: [], // 特殊日期不必须打卡
        overtimeRule: 1,
        planName: "规则名称",
        planType: 1,
        punchRange: 3,
        punchTimeList: [], // 打卡时间
        remindAfter: 0,
        remindBefore: 0,
        reportList: [],
        staffList: [],
        takeEffect: 2,
        tmpAttendShiftId: "",
        whitelist: [],
        wifiList: [],
        workDayRuleDTO: []
      },
      showUsers: false, // 添加打卡人员弹窗
      showWhiteList: false, // 显示白名单
      showReportList: false,
      showNoUseClock: false,
      showCardTime: false,
      showCardDate: false,
      addFreeCard: false,
      freeCard: {},
      editor: this.$route.params.id,
      companyId: this.$store.state.hr.companyId,
      companyName: this.$store.state.hr.companyName,
      /* 自由上下班 */
      workWeekList: ["星期一", "星期二", "星期三", "星期四", "星期五"],
      whiteOptions: {},
      /* 汇报人员 */
      reportUserOptions: {},
      /* 打卡人员数组 */
      usersList: {},
      postRules: {
        id: "",
        companyId: this.$store.state.hr.companyId,
        deptList: [],
        locationList: [],
        needPunchDateList: [],
        noNeedPunchDateList: [],
        punchTimeList: [],
        reportList: [],
        staffList: [],
        whitelist: [],
        wifiList: [],
        maxMakeUpCounts: -1,
        isMakeUp: true /* 1-是,0-否是否补卡申请 */,
        isSynchLegalHoliday: true /* 1-是,0-否是否同步中国节假日 */,
        isTakePhoto: false /* 1-是,0-否员工打卡时必须拍照 */,
        isOnlyPhoto: true /* 备注不允许上传本地图片,只能拍照;1-是,0-否只能拍照 */,
        isRemind: true /* 1-是,0-否是否手机提醒 */,
        planType: 1 /* 1-固定时间上下班,2-按班次上下班,3-自由上下班方案类型 */,
        planName: "",
        overtimeRule: 1 /* 1-以加班申请为准,2-以打卡时间为准,3-以加班申请核算打卡记录加班规则 */,
        punchRange: 3 /* 1-允许记录为地点异常,2-允许记录为正常外勤,3-不允许 */,
        remindAfter: 0 /* 下班后x分钟 */,
        remindBefore: 0 /* 上班前x分钟*/,
        takeEffect: 2 /* 1-明日生效，2-立即生效生效时间 */
      },
      form: this.$form.createForm(this, { name: "coordinated" }),
      holidays: true,
      /* addwifi */
      wifiOptions: {},
      noUseClockOptions: {},
      cardPositionOptions: {},
      doWorkRulesOptions: {},
      timeList: {},
      editIndex: -1,
      cardDateOptions: {},
      userOptions: {},
      uploadImgOptions: {},
      dataSource: [],
      isChooseStaff: false,
      isChooseStaff2: false,
      isEdit: false, // 判断是编辑规则页面还是添加规则页面
      // defaultSelectedKeys: [],
      defaultSelectedKeys2: [],
      initTimeList,
      editDateIndex: -1,
      initNeed,
      needPunchDate: {},
      initNoNeed,
      noNeedPunchDate: {},
      editNoUseIndex: -1,
      isPX: false,
      visible: false,
      dateJson
    };
  },
  computed: {
    ...mapState(["hr"]),
    /* 补卡次数 */
    cardTimes() {
      let i = 100;
      const box = [];
      while (i > -2) {
        box.push({
          name: i === -1 ? `无限次` : `${i}次`,
          time: i
        });
        i--;
      }
      return box;
    },
    defaultSelectedKeys() {
      return this.postRules.staffList.map(item => item.empInfoId);
    }
  },
  watch: {
    /* postRules */
    /*    postRules: {
         handler(val) {

         },
         deep: true
       } */
  },
  created() {
    /* 查询部门下的人员 */
    // this.getUsersList();
    /*   if (this.editor != 0) {
        this.getPunchCard();
      } */
    if (this.$route.params.id !== "0") {
      this.isEdit = true;
      this.getPunchCard();
    }
  },

  methods: {
    // 添加员工
    onEmployeeSelectChange(value) {
      this.postRules.staffList = JSON.parse(JSON.stringify(value));
      this.postRules.staffList.map((item, index, arr) => {
        this.postRules.staffList[index].empInfoId = item.id;
        this.postRules.staffList[index].empInfoName = item.name;
      });
      // this.defaultSelectedKeys = value.map(item => item.id)
    },
    onEmployeeSelectChange2(value) {
      let flag = false;
      this.postRules.staffList.forEach((item, index) => {
        if (item.id === value.id) {
          flag = true;
          return;
        }
      });
      if (flag) {
        this.$message.error("白名单人员应在打卡人员中！");
        return;
      }
      this.postRules.whitelist = JSON.parse(JSON.stringify(value));
      this.postRules.whitelist.map((item, index) => {
        this.postRules.whitelist[index].empInfoId = item.id;
        this.postRules.whitelist[index].empInfoName = item.name;
      });
      this.defaultSelectedKeys2 = value.map(item => item.id);
    },
    /* 重构 */
    deleteUser(key, arr) {
      arr.splice(key, 1);
      // this.defaultSelectedKeys = this.postRules.staffList.map(item => item.id)
    },
    staffListCustom(e) {
      this.postRules.staffList = e;
    },
    /* 按班次打卡 */
    addFreeTime() {
      const needData = [...this.postRules.deptList, ...this.postRules.staffList];
      if (needData.length) {
        this.freeCard = this;
        this.addFreeCard = true;
      } else {
        this.$message.error("请选择打卡人员");
      }
    },
    /* 获取打卡详情 */
    getPunchCard() {
      Check({
        url: EditorRules.getCheckDetail + `/${this.$route.params.id}`
      }).then(({ data }) => {
        this.detail = data;

        data.isSynchLegalHoliday = Boolean(data.isSynchLegalHoliday);
        data.isTakePhoto = Boolean(data.isTakePhoto);
        data.isOnlyPhoto = Boolean(data.isOnlyPhoto);
        data.isSynchLegalHoliday = Boolean(data.isSynchLegalHoliday);
        data.isRemind = Boolean(data.isRemind);
        data.isMakeUp = Boolean(data.isMakeUp);

        const arr = data.punchTimeList[0].workWeekList.map(e => this.dateJson[e]);
        arr.sort((a, b) => a.k - b.k);
        data.punchTimeList[0].workWeekList = arr.map(e => e.v);
        this.postRules = data;
      });
    },
    /* 删除打卡部门 */
    deletedeptList(id, arr) {
      arr.find((value, i, arrs) => {
        if (value.deptId === id) return arrs.splice(i, 1);
      });
    },
    /* 白名单列表 */
    whiteEditors(e) {
      const c = JSON.parse(JSON.stringify(e));
      this.postRules.whitelist = [...c];
    },
    /* 删除白名单 */
    deleteWhiteList(i) {
      this.postRules.whitelist.splice(i, 1);
      this.defaultSelectedKeys2 = this.postRules.whitelist.map(item => item.id);
    },
    /* 位置 */
    cardPos(e) {
      let flag = false;
      this.postRules.locationList.forEach((item, index) => {
        if (e.address === item.positionName) flag = true;
      });
      if (flag) {
        this.$notification["error"]({
          message: "失败",
          description: "打卡位置不可以重复！"
        });
        return;
      }
      this.postRules.locationList.push({
        distance: e.distance,
        positionName: e.address,
        punchLatitude: e.lat,
        punchLongitude: e.lng
      });
    },
    /* Wifi */
    editorWifi(e) {
      let flag = false;
      this.postRules.wifiList.forEach((item, index) => {
        if (e.macAddr === item.macAddr && e.name === item.name) flag = true;
      });
      if (flag) {
        this.$notification["error"]({
          message: "失败",
          description: "打卡WiFi不可以重复！"
        });
        return;
      }
      if (Object.keys(e).length) {
        this.postRules.wifiList.push(e);
      }
    },
    /* 删除Wifi */
    deleteWifi(i) {
      this.postRules.wifiList.splice(i, 1);
    },
    /* 特殊日期 /必须打卡的日期*/
    editorNeedCardDate(e) {
      if (typeof e.editorIndex === "number") {
        this.postRules.needPunchDateList[e.editorIndex] = e.data;
      } else {
        this.postRules.needPunchDateList.push(e.data);
      }
    },
    /* 删除/必须打卡的日期 */
    deleteSpTime(i) {
      this.postRules.needPunchDateList.splice(i, 1);
    },
    /* 特殊日期 /不用打卡的日期 */
    editorNoUseClock(e) {
      if (typeof e.editorIndex === "number") {
        this.postRules.noNeedPunchDateList[e.editorIndex] = e.data;
      } else {
        this.postRules.noNeedPunchDateList.push(e.data);
      }
    },

    /* 删除/不用必须打卡 */
    deleteNoUseClock(i) {
      this.postRules.noNeedPunchDateList.splice(i, 1);
    },
    /* 加班规则 */
    addWorkRules(e) {
      this.postRules = { ...this.postRules, ...e };
    },
    /* 删除位置 */
    deletePos(i) {
      this.postRules.locationList.splice(i, 1);
    },
    /* 添加打卡时间 */
    addCardTime() {
      if (this.postRules.punchTimeList.length > 0) {
        this.$message.error("最多添加一条打卡时间！");
        return;
      }
      this.showCardTime = true;
      this.editIndex = -1;
      this.timeList = JSON.parse(JSON.stringify(this.initTimeList));
    },

    /* 编辑打卡时间 */
    editorPunchTime(obj, i) {
      this.showCardTime = true;
      this.editIndex = i;
      this.timeList = JSON.parse(JSON.stringify(obj));
    },

    handleTimeList(data, editIndex) {
      const arr = data.workWeekList.map(e => this.dateJson[e]);
      arr.sort((a, b) => a.k - b.k);
      data.workWeekList = arr.map(e => e.v);
      if (editIndex < 0) {
        this.postRules.punchTimeList.push(JSON.parse(JSON.stringify(data)));
      } else {
        this.postRules.punchTimeList[editIndex] = JSON.parse(JSON.stringify(data));
      }
    },

    handleTimeShow(show) {
      this.showCardTime = show;
    },

    /* 删除打卡时间 */
    deleteCardTime(i) {
      this.postRules.punchTimeList.splice(i, 1);
    },

    /* 添加打卡特殊日期 */
    addCardDate() {
      this.showCardDate = true;
      this.editDateIndex = -1;
      this.needPunchDate = JSON.parse(JSON.stringify(this.initNeed));
    },
    /* 编辑特殊打卡日期 */
    editorCardDate(obj, i) {
      this.showCardDate = true;
      this.editDateIndex = i;
      this.needPunchDate = JSON.parse(JSON.stringify(obj));
    },

    handleDateShow(show) {
      this.showCardDate = show;
    },

    handleNeedList(data, editDateIndex) {
      let flag = false;
      if (editDateIndex === -1) {
        this.postRules.needPunchDateList.forEach((item, index) => {
          if (data.daily === item.daily) {
            flag = true;
            this.$notification["error"]({
              message: "失败",
              description: "日期不可以重复！"
            });
          }
        });
        this.postRules.noNeedPunchDateList.forEach((item, index) => {
          if (data.daily === item.daily) {
            flag = true;
            this.$notification["error"]({
              message: "失败",
              description: "必须打卡日期和不用打卡日期不可以重复！"
            });
          }
        });
      }
      if (flag) return;
      if (editDateIndex < 0) {
        this.postRules.needPunchDateList.push(JSON.parse(JSON.stringify(data)));
      } else {
        this.postRules.needPunchDateList[editDateIndex] = JSON.parse(JSON.stringify(data));
      }
    },

    /* 不用打卡日期 */
    addNoUseClock() {
      this.showNoUseClock = true;
      this.editNoUseIndex = -1;
      this.noNeedPunchDate = JSON.parse(JSON.stringify(this.initNoNeed));
    },

    handleNoNeedList(data, editNoUseIndex) {
      let flag = false;
      if (editNoUseIndex === -1) {
        this.postRules.noNeedPunchDateList.forEach((item, index) => {
          if (data.daily === item.daily) {
            flag = true;
            this.$notification["error"]({
              message: "失败",
              description: "日期不可以重复！"
            });
          }
        });
        this.postRules.needPunchDateList.forEach((item, index) => {
          if (data.daily === item.daily) {
            flag = true;
            this.$notification["error"]({
              message: "失败",
              description: "必须打卡日期和不用打卡日期不可以重复！"
            });
          }
        });
      }
      if (flag) return;
      if (editNoUseIndex < 0) {
        this.postRules.noNeedPunchDateList.push(JSON.parse(JSON.stringify(data)));
      } else {
        this.postRules.noNeedPunchDateList[editNoUseIndex] = JSON.parse(JSON.stringify(data));
      }
    },

    handleNoUseShow(show) {
      this.showNoUseClock = show;
    },

    /* 编辑不用打卡日期 */
    editorNoUseCard(obj, i) {
      this.showNoUseClock = true;
      this.editNoUseIndex = i;
      this.noNeedPunchDate = JSON.parse(JSON.stringify(obj));
    },

    // 自由上下班时打卡
    punchTime() {},
    /* 打卡时间 */

    /* 添加成员 */
    addUsers({ title = "打卡人员", types = 1 }) {
      this.isChooseStaff = true;
    },
    /* 添加白名单 */
    addWhiteList({ title = "添加白名单", types = 2 }) {
      this.isChooseStaff2 = true;
    },
    /* 汇报人员 */
    addreportUser() {
      this.showReportList = true;
      this.reportUserOptions = {
        show: true,
        types: 3,
        obj: {
          reportList: this.postRules.reportList
        }
      };
    },

    /* 重构 */

    compareDate(date1, date2, time1, time2) {
      const baseDate = "2020-01-01 ";
      date1 = moment(baseDate + date1, "YYYY-MM-DD HH:mm:ss").valueOf();
      date2 = moment(baseDate + date2, "YYYY-MM-DD HH:mm:ss").valueOf();
      time1 = moment(baseDate + time1, "YYYY-MM-DD HH:mm:ss").valueOf();
      time2 = moment(baseDate + time2, "YYYY-MM-DD HH:mm:ss").valueOf();
      if (date1 > time1 && date2 < time2 && date1 < time2 && date2 > time1) {
        return false;
      } else {
        return true;
      }
    },

    compareTime(time1, time2) {
      const baseDate = "2020-01-01 ";
      time1 = moment(baseDate + time1, "YYYY-MM-DD HH:mm:ss").valueOf();
      time2 = moment(baseDate + time2, "YYYY-MM-DD HH:mm:ss").valueOf();
      if (time1 >= time2) return true;
      else return false;
    },

    judgeTime() {
      let flag1 = false;
      let flag2 = false;
      let noExist = false;
      if (this.postRules.punchTimeList === null || this.postRules.punchTimeList.length === 0) {
        flag1 = true;
      }
      if (this.postRules.needPunchDateList === null || this.postRules.needPunchDateList.length === 0) {
        noExist = true;
      }
      if (!flag1) {
        const start1 = this.postRules.punchTimeList[0].periodList[0].startPeriod;
        const end1 = this.postRules.punchTimeList[0].periodList[0].endPeriod;
        const start2 = this.postRules.punchTimeList[0].restPeriod.startPeriod;
        const end2 = this.postRules.punchTimeList[0].restPeriod.endPeriod;
        if (this.postRules.punchTimeList[0].workWeekList.length === 0) {
          flag1 = true;
        }
        if (this.compareTime(start1, end1)) flag1 = true;
        if (this.postRules.punchTimeList[0].periodList[0].hasRestPeriod) {
          if (this.compareTime(start2, end2)) flag1 = true;
          // if (this.compareDate(start2, end2, start1, end1)) flag1 = true;
        }
      }
      if (!noExist) {
        const start3 = this.postRules.needPunchDateList[0].periodList[0].startPeriod;
        const end3 = this.postRules.needPunchDateList[0].periodList[0].endPeriod;
        const start4 = this.postRules.needPunchDateList[0].restPeriod.startPeriod;
        const end4 = this.postRules.needPunchDateList[0].restPeriod.endPeriod;
        if (this.compareTime(start3, end3)) flag2 = true;
        if (this.postRules.needPunchDateList[0].periodList[0].hasRestPeriod) {
          if (this.postRules.needPunchDateList[0].periodList.length === 1) {
            if (this.compareTime(start4, end4)) flag2 = true;
            if (this.compareDate(start4, end4, start3, end3)) flag2 = true;
          }
          if (this.postRules.needPunchDateList[0].periodList.length === 2) {
            if (this.compareTime(start4, end4)) flag2 = true;
            const t = this.postRules.needPunchDateList[0].periodList[1].endPeriod;
            if (this.compareDate(start4, end4, start3, t)) flag2 = true;
          }
        }
      }
      if (flag1) {
        this.$notification["error"]({
          message: "失败",
          description: "请检查打卡时间是否设置正确！"
        });
      }
      if (!noExist && flag2) {
        this.$notification["error"]({
          message: "失败",
          description: "请检查特殊日期是否设置正确！"
        });
      }
      return flag1 || (!noExist && flag2);
    },

    judgePos() {
      let flag1 = false;
      let flag2 = false;
      if (this.postRules.wifiList.length === 0 && this.postRules.locationList.length === 0) {
        this.$notification["error"]({
          message: "失败",
          description: "请添加打卡位置！"
        });
        flag1 = true;
      }
      this.postRules.wifiList.forEach((item, index) => {
        if (!(item.macAddr && item.name)) {
          flag2 = true;
        }
      });
      if (flag2) {
        this.$notification["error"]({
          message: "失败",
          description: "Wifi选项请填写完全！"
        });
      }
      return flag1 || flag2;
    },

    saveNeedData() {
      this.form.validateFields((err, values) => {
        if (values.planName === "") {
          this.$notification["error"]({
            message: "失败",
            description: "规则名称不可以为空！"
          });
          return;
        }
        if (this.postRules.staffList.length === 0) {
          this.$notification["error"]({
            message: "失败",
            description: "打卡人员不可以为空！"
          });
          return;
        }
        if (!err) {
          this.postRules.planName = values.planName;
          this.postRules.companyId = this.$store.state.hr.companyId;
          const needData = JSON.parse(JSON.stringify(this.postRules));
          needData.isSynchLegalHoliday = Number(needData.isSynchLegalHoliday);
          needData.isTakePhoto = Number(needData.isTakePhoto);
          needData.isOnlyPhoto = Number(needData.isOnlyPhoto);
          if (this.judgeTime()) return;
          if (this.judgePos()) return;
          if (this.postRules.id) {
            if (!needData.punchTimeList[0].periodList[0].hasRestPeriod) {
              needData.punchTimeList.forEach(e => {
                e.restPeriod = {
                  startPeriod: "",
                  endPeriod: "",
                  type: false,
                  sort: 0
                };
              });
            }
            Check({
              url: EditorRules.editorCheck,
              data: needData,
              method: "PUT"
            })
              .then(data => {
                if (data.success) {
                  this.$notification["success"]({
                    message: "成功",
                    description: "修改成功"
                  });
                  this.$router.push(`/check/checkSet`);
                }
              })
              .catch(err => {
                console.log("error log --> ", err);
              });
          } else {
            if (!this.postRules.punchTimeList[0].periodList[0].hasRestPeriod) {
              this.postRules.punchTimeList.forEach(e => {
                e.restPeriod = {
                  startPeriod: "",
                  endPeriod: "",
                  type: false,
                  sort: 0
                };
              });
            }
            Check({
              url: EditorRules.checkSet,
              method: "POST",
              data: this.postRules
            })
              .then(data => {
                if (data.success) {
                  this.$router.push(`/check/checkSet`);
                  this.$notification["success"]({
                    message: "成功",
                    description: "新增成功"
                  });
                }
              })
              .catch(err => {
                console.log("error log --> ", err);
              });
          }
        }
      });
    },

    editorReportUser(e) {
      const c = JSON.parse(JSON.stringify(e));
      this.postRules.reportList = [...c];
    },

    /* 获取所有部门人员 */
    getUsersList() {
      Check({ url: Common.selectPeoInfo }).then(({ data }) => {
        this.usersList = data;
      });
    },

    /* 导出位置 */
    exportPos() {},

    /* 删除汇报人员 */
    deleteReportUser(i) {
      this.postRules.reportList.splice(i, 1);
    },

    /* 添加WIFI */
    addWIFI() {
      this.wifiOptions = {
        show: true,
        obj: {}
      };
    },

    /* 添加打卡地点 */
    addCardPosition() {
      this.cardPositionOptions = {
        show: true,
        obj: {}
      };
    },
    /* 加班规则 */
    editorDoWorkRules() {
      this.doWorkRulesOptions = {
        show: true,
        obj: {}
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.editor_content {
  padding: 20px 200px 64px 200px;
  .w110 {
    width: 110px;
  }
  .content {
    border-bottom: 1px solid #ccc;
    padding-bottom: 20px;
    margin-bottom: 40px;
  }
  .tab_title {
    background: #fafafa;
    line-height: 48px;
    border-top: 1px solid rgba(232, 232, 232, 1);
    border-bottom: 1px solid rgba(232, 232, 232, 1);
  }
  .tab_item {
    line-height: 48px;

    border-bottom: 1px solid rgba(232, 232, 232, 1);
  }
  .tab_item_top {
    border-top: 1px solid rgba(232, 232, 232, 1);
  }
  .requireLeft {
    position: relative;
    left: -12px;
  }
  .pdl {
    padding-left: 28px;
  }
}
.editorRules_btn {
  width: 100%;
  height: 64px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  right: 0px;
  bottom: 0px;
  background: #fff;
  padding-left: 224px;
}
</style>
